package org.mar.plus;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ayatsuji
 * @date 2021-11-13 11:19
 * @since
 */
public class FormatterPlus {
    private final Map<String, Object> replaceMap = new HashMap<>();
    private static final String KEY_PATTERN = "{%s}";
    private static final Pattern pattern = Pattern.compile("\\{.+?}");

    public void addReplacement(String key, Object replacement) {
        Objects.requireNonNull(replacement);
        replaceMap.put(key, replacement);
    }

    public String format(String target) {
        for (Map.Entry<String, Object> entry: replaceMap.entrySet()) {
            String key = entry.getKey();
            String replacement = getReplacement(entry);
            target = target.replace(generateKey(key), replacement);
        }
        return target;
    }

    private String getReplacement(Map.Entry<String, Object> entry) {
        String replacement = entry.getValue().toString();
        Matcher matcher = pattern.matcher(replacement);
        while (matcher.find()) {
            String matches = matcher.group();
            String replaceKey = extractKey(matches);
            String temp = replaceMap.getOrDefault(replaceKey, matches).toString();
            replacement = replacement.replace(matches, temp);
        }
        return replacement;
    }

    private String generateKey(String key) {
        return String.format(KEY_PATTERN, key);
    }

    private String extractKey(String key) {
        return key.substring(1, key.length() - 1);
    }
}
